package com.xxh.common.utils;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xxh.common.myenmu.ResultCode;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 非常重要的工具类，主要是从jwt获取用户信息的
 */

public class WebUtils extends org.springframework.web.util.WebUtils {

    public static HttpServletRequest getHttpServletRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    public static JSONObject getJwtPayload() {
        String jwtPayload = getHttpServletRequest().getHeader("payload");
        JSONObject jsonObject = JSONUtil.parseObj(jwtPayload);
        return jsonObject;
    }

    public static Long getUserId() {
        Long id = getJwtPayload().getLong("id");
        return id;
    }

    public static String getClientId() {
        String clientId = getJwtPayload().getStr("client_id");
        return clientId;
    }

    public static List<Long> getAuthorities() {
        List<String> list = getJwtPayload().get("authorities", List.class);
        List<Long> authorities = list.stream().map(Long::valueOf).collect(Collectors.toList());
        return authorities;
    }

    public static ServerHttpResponse getServerHttpResponse(ResultCode resultCode){

        return null;
    }

}
